<template>
	<view class="root">
		<view class="header">
			<text>国家励志奖学金申请</text>
		</view>

		<u-form :model="form" ref="uForm">
			<u-tag text="基本情况" shape="circleRight" />
			
			<u-form-item label="学号" label-position="top" prop="stuId">
				<u-input v-model="form.stuId" disabled/>
			</u-form-item>
			
			<u-form-item label="院系" label-position="top" prop="xueyuan">
				<u-input type="select" v-model="form.xueyuan" @click="xueyuanShow = true" :selectOpen="false" />
				<u-select @confirm="confirmXueyuan" v-model="xueyuanShow" :list="xueyuanList"></u-select>
			</u-form-item>

			<u-form-item label="专业" label-position="top" prop="major">
				<u-input   type="text"  v-model="form.major" />
				
			</u-form-item>
			
			<u-form-item label="年级"  label-position="top" prop="level">
				<view class="">
					<u-radio-group v-model="form.level" @change="radioGroupChange">
						<u-radio @change="levelChange" v-for="(item, index) in level" :key="index"
							:name="item.name" :disabled="item.disabled">
							{{item.name}}
						</u-radio>
					</u-radio-group>
				</view>
			</u-form-item>
			
			<u-form-item label="班级" label-position="top" prop="cla">
				<u-input  v-model="form.cla" />
			</u-form-item>

			<u-form-item label="姓名" label-position="top" prop="name">
				<u-input v-model="form.name" />
			</u-form-item>
			
			<u-form-item label="性别" label-position="top" prop="gender">
				<u-radio-group v-model="form.gender" @change="radioGroupChange">
					<u-radio @change="radioChange" v-for="(item, index) in sexList" :key="index" :name="item.name"
						:disabled="item.disabled">
						{{item.name}}
					</u-radio>
				</u-radio-group>
			</u-form-item>
			
			<u-form-item label="政治面貌" label-position="top" prop="political">
				<u-radio-group v-model="form.political" @change="radioGroupChange">
					<u-radio @change="radioChange" v-for="(item, index) in politicalList" :key="index" :name="item.name"
						:disabled="item.disabled">
						{{item.name}}
					</u-radio>
				</u-radio-group>
			</u-form-item>

			<u-form-item label="民族" label-position="top" prop="nation">
				<u-input  type="select"  @click="nationShow = true" v-model="form.nation" />
			</u-form-item>

			<u-form-item label="入学年月" label-position="top" prop="schoolYear">
				<u-input  type="select" @click="dateShow = true;dateStatus = 'schoolYear'" v-model="form.schoolYear" />
			</u-form-item>

			<u-form-item label="家庭困难等级" label-width="200" label-position="top" prop="kunnanLevel">
				<view class="">
					<u-radio-group v-model="form.kunnanLevel" @change="radioGroupChange">
						<u-radio @change="radioChange" v-for="(item, index) in kunnanLevel" :key="index"
							:name="item.name" :disabled="item.disabled">
							{{item.name}}
						</u-radio>
					</u-radio-group>
				</view>
			</u-form-item>

			<u-form-item label="联系电话" label-position="top" prop="tel">
				<u-input v-model="form.tel" />
			</u-form-item>

			<u-form-item label="身份证号" label-position="top" prop="sfId">
				<u-input v-model="form.sfId" />
			</u-form-item>


			

			<u-form-item :border-bottom="false">
				<u-tag text="学习情况" shape="circleRight" />
			</u-form-item>
			
			<u-form-item label="成绩排名总人数" label-position="top" prop="classNum">
				<u-input v-model="form.classNum" type="number"/>
			</u-form-item>

			<u-form-item label="学习成绩排名(按班级)" label-position="top" prop="classRank">
				<u-input v-model="form.classRank" type="number"/>
			</u-form-item>
			
			<u-form-item label="综合考评总人数" label-position="top" prop="comEvalNum">
				<u-input v-model="form.comEvalNum" type="number"/>
			</u-form-item>

			<u-form-item label="综合考评排名(按班级)" label-position="top" prop="comEval">
				<u-input v-model="form.comEval" type="number"/>
			</u-form-item>
			
			
			
			<u-form-item label="必修课及格门数" label-position="top" prop="requiredCourseNumPass">
				<u-input v-model="form.requiredCourseNumPass" type="number"/>
			</u-form-item>
			
			<u-form-item label="必修课门数" label-position="top" prop="requiredCourseNum">
				<u-input v-model="form.requiredCourseNum" type="number"/>
			</u-form-item>
			
			

			<u-form-item :border-bottom="false">
				<u-tag text="获奖情况(非必填)" shape="circleRight" />
			</u-form-item>

			<u-form-item>
				<u-button @click="openPop" :ripple="true" ripple-bg-color="#909399" size="medium" shape="square">
					添加</u-button>
			</u-form-item>

			<u-form-item :border-bottom="false">
				<u-tag style="margin-right: 5px;" v-for="(item,index) in form.awardinfo" type="info" mode="plain"
					:text="item.awardName" closeable @close="tagClick(index)" />
			</u-form-item>

			<u-form-item :border-bottom="false">
				<u-tag text="更多" shape="circleRight" />
			</u-form-item>

			<u-form-item label="申请理由" label-position="top" prop="applyReason">
				<u-input maxlength="150" type="textarea" height="200" :placeholder="resonPlaceholder" v-model="form.applyReason" />
				<text style="float: right;">{{form.applyReason?form.applyReason.length : 0}}/150</text>
			</u-form-item>
			
			<u-form-item label="推荐理由(第三人称)" label-position="top" prop="recommendReason">
				<u-input maxlength="100" type="textarea" height="200" :placeholder="recommendPlaceholder" v-model="form.recommendReason" />
				<text style="float: right;">{{form.recommendReason?form.recommendReason.length : 0}}/100</text>
			</u-form-item>

		</u-form>
		
		<u-button @click="submit">提交</u-button>


		<!-- 以下是弹出层组件 -->
		<view>
			<u-form :model="form2" ref="uForm2">
				<!-- 添加获奖情况弹出层 -->
				<u-popup v-model="popShow" mode="bottom" :closeable="true">
					<view class="addAwards">

						<u-form-item :border-bottom="false">
							<u-tag text="获奖时间必须为2022年09月-2023年08月之间" mode="plain" />
						</u-form-item>

						<u-form-item label="获奖时间" label-position="top" prop="awardTime">
							<u-input :selectOpen="dateShow" type="select" @click="dateShow = true;dateStatus = 'AwardTime'"
								v-model="form2.awardTime" />

						</u-form-item>

						<u-form-item label="奖项名称" label-position="top" prop="awardName">
							<u-input v-model="form2.awardName" />
						</u-form-item>

						<u-form-item label="颁奖单位" label-position="top" prop="awardUnit">
							<u-input v-model="form2.awardUnit" />
						</u-form-item>
						
						<!-- <u-form-item label="添加获奖证明" label-position="top" prop="files">
							<u-input :selectOpen="hjShow" @click="navHuojiang" :value="'已添加'+picNum+'张照片'"  type="select"  />
						</u-form-item> -->

						<u-form-item :border-bottom="false">
							<u-button size="medium" @click="addAwards">确认</u-button>
						</u-form-item>


					</view>
				</u-popup>
			</u-form>

		</view>
		<!-- 日期选择组件 -->
		<view class="">
			<u-picker mode="time"  v-model="dateShow" :params="params" @confirm="dateChange"></u-picker>
			<!-- <u-calendar v-model="dateShow" mode="date" @change="dateChange"></u-calendar> -->
		</view>
		
		<!-- 民族选择组件 -->
		<view class="">
			<u-picker @confirm="nationChange" mode="selector" v-model="nationShow"  :default-selector="[0]" :range="nationList"></u-picker>
		</view>
		
		<!-- 专业选择组件 -->
		<view class="">
			<u-picker @confirm="majorChange" mode="selector" v-model="majorShow"  :default-selector="[0]" :range="majorList" range-key="major"></u-picker>
		</view>
		
		<view class="">
			<u-picker @confirm="claChange" mode="selector" v-model="claShow"  :default-selector="[0]" :range="claList" range-key="cla"></u-picker>
		</view>

		<view>
			<u-toast ref="uToast" />
		</view>
	</view>
</template>

<script>
	Date.prototype.format = function(fmt) {
		var o = {
			"M+": this.getMonth() + 1, //月份
			"d+": this.getDate(), //日
			"h+": this.getHours(), //小时
			"m+": this.getMinutes(), //分
			"s+": this.getSeconds(), //秒
			"q+": Math.floor((this.getMonth() + 3) / 3), //季度
			"S": this.getMilliseconds() //毫秒
		};
	
		if (/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
		}
	
		for (var k in o) {
			if (new RegExp("(" + k + ")").test(fmt)) {
				fmt = fmt.replace(
					RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
			}
		}
	
		return fmt;
	}
	var national = require("../../../../static/national.js");
	var major = require("../../../../static/major.js")
	import {getXueyuanList, getKunnanInfo} from "@/api/kunnan.js"
	import {addGuoli,getGuoli} from "@/api/zizhu.js"
	import {getHelpStudent} from "@/api/student.js"
	national = national.national;
	major = major.major
	var that;// 当前页面对象
	var vk; //vk依赖
	export default {
		data() {
			return {
				xueyuanList:[],
				deptList:[],
				nationList:[],
				majorList:[],
				claList:[],
				dateStatus: '',
				picNum:0,
				params: {
					year: true,
					month: true,
					day: false,
					hour: false,
					minute: false,
					second: false
				},
				picNumtext:'已上传${picNum}张照片',
				recommendPlaceholder:'以汉字为单位不得少于60个字，不能多于100字，必须以第三人称撰写，如：该生于2022学年中...。不能出现“我”字',
				resonPlaceholder: '填写申请理由。注意：填写家庭情况、在校表现。以汉字为单位不得少于120个字，不能多于150字。合理使用标点符号！',
				value: 'apple',
				level:[{
					name: '21',
					disabled: false
				},
				{
					name: '22',
					disabled: false
				}],
				kunnanLevel: [{
						name: '一般困难',
						disabled: false
					},
					{
						name: '困难',
						disabled: false
					},
					{
						name: '特别困难',
						disabled: false
					}
				],
				politicalList:[{
						name: '中共预备党员',
						disabled: false
					},
					{
						name: '共青团员',
						disabled: false
					},
					{
						name: '群众',
						disabled: false
					}],
				sexList: [{
						name: '男',
						disabled: false
					},
					{
						name: '女',
						disabled: false
					}
				],
				popShow: false,
				dateShow: false,
				nationShow:false,
				majorShow:false,
				claShow:false,
				hjShow:false,
				xueyuanShow:false,
				form: {
					deptId:'',
					xueyuan: '智能制造学院',
					name:'',
					major: '',
					gender: '',//性别
					level:'',//年级
					eduSys:'',//学制
					nation: '',
					both:'',
					political:'',
					csrq:'',
					schoolYear: '',
					stuId:uni.getStorageSync('stuId') || '',
					cla: '',
					tel: '',
					sfId:'',
					kunnanLevel: '',
					classNum: '',
					classRank: '',
					comEval: '',
					comEvalNum:'',
					requiredCourseNum:'',
					requiredCourseNumPass:'',
					awardinfo: [],
					applyReason: '',
					recommendReason:''
				},
				form2: {
					awardTime: '',
					awardName: '',
					awardUnit: '',
					// files:[]
				},
				rules: {
					name: [{
						required: true,
						message: '请输入姓名',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					major: [{
						required: true,
						message: '请输入专业名称',
						trigger: ['change', 'blur'],
					}],
					gender: [{
						required: true,
						message: '请选择性别',
						trigger: ['change', 'blur'],
					}],
					political:[{
						required: true,
						message: '请选择政治面貌',
						trigger: ['change', 'blur'],
					}],
					nation: [{
						required: true,
						message: '请输入民族',
						trigger: ['change', 'blur'],
					}],
					schoolYear: [{
						required: true,
						message: '请输入学年月',
						trigger: ['change', 'blur'],
					}],
					stuId: [{
						required: true,
						message: '请输入学号',
						trigger: ['change', 'blur'],
					}],
					cla: [{
						required: true,
						message: '请输入班级',
						trigger: ['change', 'blur'],
					}],
					tel: [{
						required: true,
						message: '请输入联系电话',
						trigger: ['change', 'blur'],
					},{
						trigger: ['change', 'blur'],
						message: '手机号码不正确',
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// this.$u.test.mobile()就是返回true或者false的
							return this.$u.test.mobile(value);
						},
						
					}],
					sfId: [{
						required: true,
						message: '请输入身份证号',
						trigger: ['change', 'blur'],
						// 自定义验证函数，见上说明
						
					},{
						trigger: ['change', 'blur'],
						message: '身份证不正确',
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// this.$u.test.mobile()就是返回true或者false的
							return this.$u.test.idCard(value);
						},
						
					}],
					kunnanLevel: [{
						required: true,
						message: '请选择家庭困难等级',
						trigger: ['change', 'blur'],
					}],
					classNum: [{
						required: true,
						message: '请输入成绩排名人数',
						trigger: ['change', 'blur'],
					}],
					classRank: [{
						required: true,
						message: '请输入学习成绩排名',
						trigger: ['change', 'blur'],
					},{
						trigger: ['change', 'blur'],
						message: '学习成绩排名不在前50%',
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// this.$u.test.mobile()就是返回true或者false的
							
							if(value < (Number.parseInt(this.form.classNum )/2) || value == (Number.parseInt(this.form.classNum )/2)){
								
								return true
							}
							return false
						}
						
					}],
					comEval: [{
						required: true,
						message: '请输入综合考评排名',
						trigger: ['change', 'blur'],
					},{
						trigger: ['change', 'blur'],
						message: '综合考评排名不在前50%',
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// this.$u.test.mobile()就是返回true或者false的
							
							if(value < (Number.parseInt(this.form.comEvalNum)/2) || value == (Number.parseInt(this.form.comEvalNum )/2)){
								
								return true
							}
							return false
						}
						
					}],
					comEvalNum: [{
						required: true,
						message: '请输入综合考评总人数',
						trigger: ['change', 'blur'],
					}],
					applyReason: [{
						required: true,
						message: '请输入申请理由',
						trigger: ['change', 'blur'],
					}, {
						min: 120,
						message: '申请理由不得少于120个字，不能多于150字',
						trigger: 'change'
					},{
						max: 150,
						message: '申请理由不得少于120个字，不能多于150字',
						trigger: 'change'
					}],
					recommendReason: [{
						required: true,
						message: '请输入推荐理由',
						trigger: ['change', 'blur'],
					}, {
						min: 60,
						message: '推荐理由不得少于60个字，不能多于100字',
						trigger: 'change'
					},{
						max: 100,
						message: '推荐理由不得少于60个字，不能多于100字',
						trigger: 'change'
					}],
					requiredCourseNum:[{
						required: true,
						message: '请输入必修课门数',
						trigger: ['change', 'blur'],
					}],
					requiredCourseNumPass:[{
						required: true,
						message: '请输入必修课及格门数',
						trigger: ['change', 'blur'],
					}]
				},
				rules2: {
					awardTime: [{
						required: true,
						message: '请选择获奖时间',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					awardName: [{
						required: true,
						message: '请输入获取名称',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					awardUnit: [{
						required: true,
						message: '请输入颁奖单位',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					
				}
			};
		},
		methods: {
			extractBirthdate(idNumber) {
			  // 使用正则表达式提取身份证号码中的出生日期部分（前14位）
			  const regex = /^(\d{6})(\d{4})(\d{2})(\d{2})\d{2}(\d)(\d|X)$/;
			  const matches = idNumber.match(regex);
			
			  if (matches) {
			    const year = parseInt(matches[2]);
			    const month = parseInt(matches[3]);
			    const day = parseInt(matches[4]);
			    return { year, month, day };
			  } else {
			    return null; // 身份证号码格式不正确
			  }
			},
			submit() {
				const _that = this
				this.$refs.uForm.validate(valid => {
					if (valid) {
						console.log('验证通过');
						console.log(this.form.awardinfo)
						this.form.awardinfo.forEach((val,i)=>{
							this.form['awardTime'+(i+1)] = val.awardTime
							this.form['awardName'+(i+1)] = val.awardName
							this.form['awardUnit'+(i+1)] = val.awardUnit
						})
						
						
						//获取出生年月
						let {year,month} = this.extractBirthdate(this.form.sfId)
						this.form.csrq = year + '年'+month +'月'
						
						addGuoli(this.form).then(data=>{
							let [err,res ] = data
							console.log(res)
							vk.alert(res.data.msg || err);
						})
					} else {
						console.log('验证失败');
					}
				});
			},
			confirmXueyuan(e){
				console.log(e)
				this.form.deptId = e[0].value
				this.form.xueyuan = e[0].label
			},
			openPop() {
				this.picNum = 0
				uni.removeStorage({
					key:'pic',
					success: () => {
						if (this.form.awardinfo.length == 3) {
							this.$refs.uToast.show({
								title: '最多添加3个获奖情况',
								type: 'warning',
							})
							return
						}
						this.form2 = {
							awardTime: '',
							awardName: '',
							awardUnit: '',
						}
						this.popShow = true
					},
					fail: () => {
						if (this.form.awardinfo.length == 3) {
							this.$refs.uToast.show({
								title: '最多添加3个获奖情况',
								type: 'warning',
							})
							return
						}
						this.form2 = {
							awardTime: '',
							awardName: '',
							awardUnit: '',
							// files:[]
						}
						this.popShow = true
					}
				})
				


			},
			addAwards() {
				this.$refs.uForm2.validate(valid => {
					if (valid) {
						console.log('验证通过');
						this.popShow = false
						this.form.awardinfo.push(this.form2)

						console.log(this.form.awardinfo)
					} else {
						console.log('验证失败');
					}
				});

			},
			// 复用日期组件
			dateChange(e) {
				console.log(e)
				switch (this.dateStatus) {
					case 'AwardTime':
						// 获奖时间
						this.form2.awardTime = String(e.year) + '-' + String(e.month)  
						break
						// 入学时间
					case 'schoolYear':
						this.form.schoolYear = String(e.year) + '年' + String(e.month) + '月'
						break
				}

			},
			tagClick(e) {
				console.log(e)
				this.form.awardinfo.splice(e, 1)
			},
			radioChange(e) {
				// console.log(e);
			},
			// 选中任一radio时，由radio-group触发
			radioGroupChange(e) {
				// console.log(e);
			},
			nationChange(e){
				this.form.nation = this.nationList[e]
				// console.log(this.form.nation)
			},
			majorChange(e){
				this.form.major = major[0].list[e].major
				this.claList = major[0].list[e].cla
				// console.log(e)
			},
			levelChange(e){
				if(this.form.level == ''){
					return
				}
				
			},
			claChange(e){
				
				this.form.cla = this.claList[e]
			},
			navHuojiang(){
				uni.navigateTo({
					url:'../huojiang/huojiang'
				})
			}
		},
		async onLoad(options) {
			that = this;
			vk = that.vk
			that.options = options
			this.nationList = national
			this.majorList = major[0].list
			
			
			//获取学院列表
			let [errx,xueyuanList] = await getXueyuanList()
			this.deptList = xueyuanList.data.rows
			this.xueyuanList = xueyuanList.data.rows.map((val)=>{
				return {label:val.deptName,value:val.deptId}
			})
			
			 let [err,guoliRes] =  await  getGuoli()
			 
			if(guoliRes.data.data){
				
				//处理获奖
				for(let i= 1;i<4;i++){
					
					console.log(guoliRes.data.data['awardName' +i])
					if(guoliRes.data.data['awardName' +i]){
						let aw = {
							awardTime: guoliRes.data.data['awardTime' +i],
							awardName: guoliRes.data.data['awardName' +i],
							awardUnit: guoliRes.data.data['awardUnit' +i],
						}
						this.form.awardinfo.push(aw)
					}
					
					
				}
				this.form = {...this.form,...guoliRes.data.data}
				//获取deptId
				for(let i = 0;i<this.deptList.length;i++){
					if(this.deptList[i].deptName == guoliRes.data.data?.xueyuan){
						this.form.deptId = this.deptList[i].deptId
						
					}
				}
			}
			else {
				
				
				// console.log(xueyuanList)
				//获取学生信息
				getHelpStudent().then(data =>{
					let [err, res] = data
					// console.log(res)
					this.form = {...this.form,...res.data.data}
					
					//获取deptId
					for(let i = 0;i<this.deptList.length;i++){
						if(this.deptList[i].deptName == res.data.data?.xueyuan){
							this.form.deptId = this.deptList[i].deptId
							
						}
					}
					console.log(this.form)
				})
			}	
			
			
			
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
			this.$refs.uForm2.setRules(this.rules2);

		},
		onShow() {

			

		}
	};
</script>

<style scoped>
	.root {
		padding: 20px;
		background-color: #ffffff;
	}

	.header {
		display: flex;
		justify-content: center;
		margin: 0 0 10px;
	}

	.header text {
		font-size: 18px
	}

	.addAwards {

		padding: 20px;
	}
</style>
